package com.jiahao.material.controllers;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jiahao.material.entity.Result;
import com.jiahao.material.entity.User;
import com.jiahao.material.entity.UserRole;
import com.jiahao.material.mapper.UserRoleMapper;
import com.jiahao.material.services.ITokenEntityService;
import com.jiahao.material.services.IUserService;
import com.jiahao.material.utils.MD5Util;
import com.jiahao.material.utils.ResultUtil;
import com.jiahao.material.utils.TokenUtil;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import lombok.Data;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.security.provider.MD5;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;

@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private ITokenEntityService tokenEntityService;




    /**
     * 登录用户
     * @param map
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody Map<String,Object> map) throws Exception{
        String userName=map.get("userName").toString();
        String password=map.get("password").toString();
        String key = map.get("key").toString();
        String verCode = map.get("verCode").toString().toUpperCase().trim();

        String s = null;
        try {
            s = redisTemplate.opsForValue().get(key).trim();
        } catch (Exception e) {
            return ResultUtil.fail("验证码失效");
        }

        if (!verCode.equals(s)){
            return ResultUtil.fail("验证码错误!");
        }


        User userByUserName = userService.getUserByUName(userName);
        if (userByUserName==null){
            return ResultUtil.fail("用户不存在!");
        }

        if (userByUserName.getStatus().equals("00")){
            return ResultUtil.fail("用户已被冻结!");
        }

        if (!userByUserName.getPassword().equals(MD5Util.encryptPassword(userName,password))){
            return ResultUtil.fail("密码错误!");
        }else{
            Result success = ResultUtil.success("登录成功!");
            success.setData(tokenEntityService.createToken(userByUserName.getId()));
            return success;
        }
    }


    /**
     * 退出登录,更新token
     * @param request
     * @return
     * @throws Exception
     */
    @GetMapping("/logout")
    public Result logout( HttpServletRequest request) throws Exception{
        String token = TokenUtil.getToken(request);
        tokenEntityService.logout(token);
        return ResultUtil.success("退出成功!");
    }

    /**
     * 验证码
     * @param request
     * @param response
     * @return
     */
    @GetMapping("/captcha")
    public Result captcha(HttpServletRequest request, HttpServletResponse response){
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 5);
        specCaptcha.setCharType(Captcha.TYPE_NUM_AND_UPPER);
        String verCode = specCaptcha.text().toUpperCase();
        String verKey = UUID.randomUUID().toString().replace("-","");
        redisTemplate.opsForValue().set(verKey,verCode,60, TimeUnit.SECONDS);
        Result success = ResultUtil.success(verKey,specCaptcha.toBase64());
        return success;
    }

    /**
     * 添加角色
     * @param map
     * @return
     * @throws Exception
     */
    @RequiresPermissions("addUser")
    @PostMapping("/add")
    @Transactional
    public Result add(@RequestBody Map<String,Object> map) throws Exception{
        //添加用户
        User user = new User();
        user.setUserName(map.get("userName").toString());
        user.setPassword(MD5Util.encryptPassword(map.get("userName").toString(),map.get("password").toString()));
        user.setEmail(map.get("email").toString());
        user.setIconUrl(map.get("iconUrl").toString());
        user.setNickName(map.get("nickName").toString());
        user.setPhone(map.get("phone").toString());
        user.setRealName(map.get("realName").toString());
        user.setSex(map.get("sex").toString());
        user.setStatus("01");
        userService.save(user);

        //添加角色关系
        List<String> roles = (List<String>) map.get("roles");
        if (roles!=null && !roles.isEmpty()){
            UserRole userRole = new UserRole();
            userRole.setUid(user.getId());
            for (String role : roles) {
                userRole.setRid(role);
                userRoleMapper.insert(userRole);
            }
        }

        return ResultUtil.success("添加用户成功!");
    }

    /**
     * 通过id查询角色
     * @param id
     * @return
     * @throws Exception
     */
    @GetMapping("/byId/{id}")
    public Result getById(@PathVariable String id) throws Exception{
        User byId = userService.getUserById(id);
        return ResultUtil.success("",byId);
    }

    /**
     * 校验用户名是否存在
     * @param map
     * @return
     */
    @PostMapping("/checkByUName")
    public Result checkByUName(@RequestBody Map<String,Object> map){
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("userName",map.get("userName").toString());
        User one = userService.getOne(userQueryWrapper);
        //"0"表示没有
        String e="0";
        if (one!=null)
            e = one.getId().equals(map.get("id").toString())?"0":"1";
        return ResultUtil.success(e);
    }

    /**
     * 校验密码
     * @param map
     * @return
     */
    @PostMapping("/checkPWD")
    public Result checkPWD(@RequestBody Map<String,Object> map){
        String userName =map.get("userName").toString();
        String password = map.get("oldPassword").toString();
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("userName",userName);
        User one = userService.getOne(userQueryWrapper);
        //定义01为通过
        Result success = ResultUtil.success("01");
        if (!one.getPassword().equals(MD5Util.encryptPassword(userName,password))){
            success.setMessage("00");
        }

        return success;
    }

    /**
     * 分页查询
     * @param map
     * @return
     * @throws Exception
     */
    @PostMapping("/page")
    public Result getByPage(@RequestBody Map<String,Object> map) throws Exception{
        int pageSize = map.get("pageSize") == null ? 10 : Integer.parseInt(map.get("pageSize").toString());
        int currentPage = map.get("currentPage") == null ? 1 : Integer.parseInt(map.get("currentPage").toString());
        Page<User> page = new Page<>(currentPage,pageSize);
        IPage<User> page1 = userService.getUsersByPage(page,map);
        return ResultUtil.success("",page1);
    }

    /**
     * 更新用户
     * @param map
     * @return
     * @throws Exception
     */
    @RequiresPermissions("updateUser")
    @PutMapping("/update")
    @Transactional
    public Result update(@RequestBody Map<String,Object> map) throws Exception{
        //添加用户
        User user = new User();
        user.setId(map.get("id").toString());
        user.setEmail(map.get("email").toString());
        user.setIconUrl(map.get("iconUrl").toString());
        user.setNickName(map.get("nickName").toString());
        user.setPhone(map.get("phone").toString());
        user.setRealName(map.get("realName").toString());
        user.setSex(map.get("sex").toString());
        userService.updateById(user);

        //添加角色关系
      if (map.containsKey("roles")){
          //先删除
          QueryWrapper<UserRole> userRoleQueryWrapper = new QueryWrapper<>();
          userRoleQueryWrapper.eq("uid",map.get("id").toString());
          userRoleMapper.delete(userRoleQueryWrapper);

          //再添加
          List<String> roles = (List<String>) map.get("roles");
          if (roles!=null && !roles.isEmpty()){
              UserRole userRole = new UserRole();
              userRole.setUid(user.getId());
              for (String role : roles) {
                  userRole.setRid(role);
                  userRoleMapper.insert(userRole);
              }
          }
      }

        return ResultUtil.success("更新角色成功!");
    }

    /**
     * 更新状态
     * @param map
     * @return
     * @throws Exception
     */
    @RequiresPermissions("updateUser")
    @PutMapping("/status")
    public Result updateStatus(@RequestBody Map<String,Object> map) throws Exception{
        UpdateWrapper<User> userUpdateWrapper = new UpdateWrapper<>();
        userUpdateWrapper.eq("id",map.get("id").toString()).set("status",map.get("status").toString());
        userService.update(userUpdateWrapper);
        return ResultUtil.success("更新状态成功!");
    }


    /**
     * 根据id删除用户
     * @param id
     * @return
     * @throws Exception
     */
    @RequiresPermissions("delUser")
    @DeleteMapping("/del/{id}")
    @Transactional
    public Result delById(@PathVariable String id) throws Exception{
        //删除用户
        userService.removeById(id);
        //删除用户的角色
        QueryWrapper<UserRole> userRoleQueryWrapper = new QueryWrapper<>();
        userRoleQueryWrapper.eq("uid",id);
        userRoleMapper.delete(userRoleQueryWrapper);
        return ResultUtil.success("删除用户成功!");
    }

    /**
     * 根据ids批量删除用户
     * @param ids
     * @return
     * @throws Exception
     */
    @RequiresPermissions("delUser")
    @PostMapping("/dels")
    @Transactional
    public Result delByIds(@RequestBody List<String> ids) throws Exception{
        //删除用户
        userService.removeByIds(ids);
        //删除用户的角色
        QueryWrapper<UserRole> userRoleQueryWrapper = new QueryWrapper<>();
        userRoleQueryWrapper.in("uid",ids);
        userRoleMapper.delete(userRoleQueryWrapper);
        return ResultUtil.success("删除用户成功!");
    }

    /**
     * 重置用户密码
     * @param map
     * @return
     * @throws Exception
     */
    @RequiresPermissions("resetPWD")
    @PostMapping("/resetPWD")
    public Result resetPWD(@RequestBody Map<String,Object> map) throws Exception{
        UpdateWrapper<User> userUpdateWrapper = new UpdateWrapper<>();
        userUpdateWrapper.eq("id",map.get("id").toString()).set("password",MD5Util.encryptPassword(map.get("userName").toString(),map.get("password").toString()));
        userService.update(userUpdateWrapper);
        return ResultUtil.success("重置密码成功!");
    }

    /**
     * 上传头像
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping("/icon")
    public Result uploadIcon(@RequestBody MultipartFile file) throws Exception{
        if (file.isEmpty()){
            return null;
        }
        String originName=file.getOriginalFilename();
        String suffixName = originName.substring(originName.lastIndexOf("."));  // 后缀名
        String filePath = ClassUtils.getDefaultClassLoader().getResource("").getPath()+"static/icons"; // 上传后的路径
        String fileName= UUID.randomUUID().toString().replaceAll("-","")+suffixName;
        File file1=new File(filePath,fileName);
        if (!file1.getParentFile().exists()){
            file1.getParentFile().mkdirs();
        }
        try {
            file.transferTo(file1);
            String url="http://127.0.0.1:8090/icons/"+fileName;
            return ResultUtil.success(url);
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        }
    }


}
